package com.mf.service.impl.basic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.emuns.enumsPublic.EnumPublicEnableOrDisable;
import com.mf.entity.req.basic.ReqUser;
import com.mf.exception.GraceException;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.mf.entity.dto.basic.DtoUser;
import com.mf.entity.req.basic.search.SearchReqUser;
import com.mf.mapper.basic.MapperUser;
import com.mf.service.basic.ServiceUser;


@Service
public class ImplServiceUser extends ServiceImpl<MapperUser, DtoUser> implements ServiceUser {
    @Resource
    private PasswordEncoder passwordEncoder;


    /**
     * 参数查询条件
     * neRoleId
     */
    @Override
    public LambdaQueryWrapper<DtoUser> fillParams(SearchReqUser params) {
        LambdaQueryWrapper<DtoUser> wrapper = loadQw();
        wrapper.orderByDesc(DtoUser::getId);
        if (StringUtils.isNotBlank(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoUser::getNick, params.getKey())
                        .or()
                        .like(DtoUser::getAccount, params.getKey())
                ;
            });
        }


        wrapper.eq(ObjectUtils.isNotEmpty(params.getStatus()), DtoUser::getStatus, params.getStatus());
        return wrapper;
    }

    /**
     * 管理员修改密码
     */
    @Override
    public void adminUpdatePwd(ReqUser reqUser) {
        DtoUser dtoUser = findCheckById(reqUser.getId(), true);
        dtoUser.setPassword(passwordEncoder.encode(reqUser.getPassword()));
        updateById(dtoUser);
    }

    /**
     * 用户修改密码
     */
    @Override
    public void updatePwd(ReqUser reqUser) {
        DtoUser dtoUser = findCheckById(reqUser.getId(), true);
        GraceException.display(!passwordEncoder.matches(reqUser.getPassword(), dtoUser.getPassword()), "密码错误");
        dtoUser.setPassword(passwordEncoder.encode(reqUser.getNewPassword()));
        updateById(dtoUser);
    }

    /**
     * 通过账号查询用户
     */
    @Override
    public DtoUser findByAccount(String account) {
        LambdaQueryWrapper<DtoUser> wrapper = loadQw();
        wrapper.eq(DtoUser::getAccount, account)
                .eq(DtoUser::getStatus, EnumPublicEnableOrDisable.ENABLE.getCode());
        return getOne(wrapper);
    }

}